package com.atguigu.tingshu.common.login;

import cn.hutool.core.bean.BeanUtil;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.user.UserInfo;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import jakarta.servlet.http.HttpServletRequest;
import lombok.SneakyThrows;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Component
@Aspect
public class GuiGuLoginAspect {
    @Autowired
    private RedisTemplate redisTemplate;
    @SneakyThrows
    @Around("execution(* com.atguigu.tingshu.*.api.*.*(..))&&@annotation(guiGuLogin)")
    public Object loginAspect(ProceedingJoinPoint proceedingJoinPoint,GuiGuLogin guiGuLogin) {
        //获取请求对象
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        //  转化为ServletRequestAttributes
        ServletRequestAttributes servletRequestAttributes= (ServletRequestAttributes) requestAttributes;
       //获取请求上下文
        HttpServletRequest request = servletRequestAttributes.getRequest();
        //获取token
        String token = request.getHeader("token");
        //格式化token
        String tokenKey=RedisConstant.USER_LOGIN_KEY_PREFIX+ token;
        //通过tokenkey获redis中是否包含user_info信息
        UserInfoVo userInfoVo = (UserInfoVo)redisTemplate.opsForValue().get(tokenKey);
        if(BeanUtil.isEmpty(userInfoVo)&&guiGuLogin.require()){
            throw new GuiguException(ResultCodeEnum.LOGIN_AUTH);
        }
        //用户不为空，将用户信息存入本地线程
        if(BeanUtil.isNotEmpty(userInfoVo)){
            AuthContextHolder.setUserId(userInfoVo.getId());
            AuthContextHolder.setUsername(userInfoVo.getNickname());
        }
        //放行执行目标方法
        Object proceed = proceedingJoinPoint.proceed();
        //删除本地线程中的
        AuthContextHolder.removeUserId();
        AuthContextHolder.removeUsername();


        return proceed;
    }
}
